package server.web.api.webuser;

import com.alibaba.fastjson.JSONObject;
import server.web.WebUser;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class Query extends HttpServlet {
    private static final long serialVersionUID = 5739771025727322462L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/plain");

        HttpSession se = req.getSession(false);
        JSONObject data = new JSONObject();
        if (se == null || se.getAttribute("user") == null) {
            data.put("code", false);
            data.put("data", URLEncoder.encode("未登录", "utf-8"));
        } else {
            WebUser user = (WebUser) se.getAttribute("user");
            String s = null;
            int i = 0;
            while (i < 30 * 1000 / 500 && s == null) {
                s = user.check();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
            }
            if (i >= 30 * 1000 / 500) {
                data.put("code", false);
                data.put("data", URLEncoder.encode("未收到消息", "utf-8"));
            } else {
                data.put("code", true);
                data.put("data", URLEncoder.encode(s, "utf-8"));
            }
        }
        resp.getWriter().print(JSONObject.toJSONString(data));
    }
}